<template>
	<div class="question">
		<div class="content-div">
			<Row style="margin-top:10px">
				<Col span="14" class="table-form-input-select-col">
					<span class="alltitle" style="line-height:30px"><router-link to="项目列表"> 项目列表</router-link>>预备员工专区>培训</span>
				</Col>
				<Col span="3" offset="3">
					<Button type="primary" @click="addTrainContentClick">增加培训内容</Button>
				</Col>		
                <Col span="3">
                    <Button type="primary" @click="addTrainExamineClick">增加培训考核</Button>
                </Col>      		
			</Row>
		</div>
		<div class="content-div" style="margin-top:10px">
			<Table border stripe :columns="columns" :data="data" ref="table" style="overflow: visible"></Table>
		</div>
<!-- 		<div class="content-div" align="center">
			<Page @on-change="changepage" 
				:total="pageData.total" 
				:current="pageData.current" 
				:page-size="pageData.pageSize" 
				style="padding:5px 5px 2px 5px;" 
				show-elevator>
			</Page>
		</div> -->
		<Modal class="modelEdit" v-model="editQuestion" width="900" :mask-closable="false" title="编辑问答" @on-ok="okEdit('editData')">
            <Form ref="editData" :model="editData" :rules="ruleformData" inline>
                <FormItem label="标题" :label-width="100" prop="title">
                    <Input class="input-item" placeholder="输入标题" v-model="editData.title"></Input>
                </FormItem>
                <FormItem label="培训说明" :label-width="100" prop="memo">
                    <Input :rows="3" type="textarea" placeholder="输入说明" v-model="editData.memo" style="width:700px;margin-left:45px"></Input>
                </FormItem>     
                <FormItem label="培训积分" :label-width="100" prop="integral" style="display: block">
                    <InputNumber :max="100" :min="1" v-model="editData.integral" style="margin-left:45px"></InputNumber>
                </FormItem>
                <FormItem label="首图" :label-width="100" prop="pic1">
                    <div class="input-item">                        
                        <img v-if="editData.picurl" :src="editData.picurl" class="avatar" @click="handleImageClick2">
                        <i v-else class="img-border el-icon-plus avatar-uploader-icon" @click="handleImageClick2">+</i>
                        <div class="up-file" style="display:none">
                            <form>
                                <input class="addinput2" accept="image/*" name="upimage" type="file" @change="uploadImage2($event)" style="display:none"/>
                            </form>
                        </div>
                    </div>
                    <Input class="input-item" placeholder="输入标题" v-model="editData.pic1" style="display:none"></Input>
                </FormItem>         
            </Form>
        </Modal>
        <Modal class="modelEdit" v-model="addTrain" width="900" :mask-closable="false" title="新增培训内容" @on-ok="okAdd('formData')">
            <Form ref="formData" :model="formData" :rules="ruleformData" inline>
                <FormItem label="标题" :label-width="100" prop="title">
                    <Input class="input-item" placeholder="输入标题" v-model="formData.title"></Input>
                </FormItem>
                <FormItem label="培训说明" :label-width="100" prop="memo">
                    <Input :rows="3" type="textarea" placeholder="输入说明" v-model="formData.memo" style="width:700px;margin-left:45px"></Input>
                </FormItem>     
                <FormItem label="培训积分" :label-width="100" prop="integral" style="display: block">
                    <InputNumber :max="100" :min="1" v-model="formData.integral" style="margin-left:45px"></InputNumber>
                </FormItem>
                <FormItem label="首图" :label-width="100" prop="pic1">
                    <div class="input-item">                        
                        <img v-if="formData.picurl" :src="formData.picurl" class="avatar" @click="handleImageClick">
                        <i v-else class="img-border el-icon-plus avatar-uploader-icon" @click="handleImageClick">+</i>
                        <div class="up-file" style="display:none">
                            <form>
                                <input class="addinput" accept="image/*" name="upimage" type="file" @change="uploadImage($event)" style="display:none"/>
                            </form>
                        </div>
                    </div>
                    <Input class="input-item" placeholder="输入标题" v-model="formData.pic1" style="display:none"></Input>
                </FormItem>         
            </Form>
        </Modal>
	</div>
</template>
<script>
export default {
    data() {
        return {
        	pageData: {
                    current: 1,
                    total: 1,
                    pageSize: 20
                },
            data: [],
            imageData: null,
            editQuestion: false,
            addTrain: false,
            formData: {
                type: 1,
            	title: '',
            	memo: '',
                pic1: '',
                integral: 0
            },
            editData: {},
            ruleformData: {
            	title: [{
            		required: true,
            		type: "string",
            		message: "请输入标题",
            		trigger: "change"
            	}],
            	memo: [{
            		required: true,
            		type: "string",
            		message: "请输入说明描述",
            		trigger: "change"
            	}],
                pic1: [{
                    required: true,
                    type: "string",
                    message: "请输入图片",
                    trigger: "change"
                }],
                integral: [{
                    required: true,
                    type: "number",
                    message: "请输入积分",
                    trigger: "change"
                }],
            },
        	columns: [
            {
                title: "序号",
                key: "id",
                width: 99,
            }, 
            {
                title: "首图",
                width: 100,
                render: (h, params) => {
                    return h("img", {
                        style: {
                            width: "60px",
                            height: "40px",
                            verticalAlign: "middle"
                        },
                        attrs: {
                            src: this.data[params.index].picurl
                        }
                    }, '')
                }
            },
            {
        		title: "标题",
                width: 300,
        		key: "title",

        	}, {
                title: "培训类型",
                width: 100,
                render: (h, params) => {
                    var t = this.data[params.index].type == 1 ? "内容" : "考核"
                    return h("span", {}, t)
                }
            }, {
        		title: "培训描述",
        		key: "memo",
        	}, {
                title: "题目积分",
                width: 100,
                key: "integral",

            }, {
        		title: "操作",
        		key: "operate",
        		width: 150,
        		render: (h, params) => {
                        return h("div", [
                            h(
                                "span", {
                                    style: {
                                        textDecoration: "underline",
                                        color: "#4b80fd",
                                        cursor: "pointer",
                                    },
                                    on: {
                                        click: () => {
                                            this.moveUp(this.data[params.index], params.index)
                                        }
                                    }
                                },
                                "上移"
                            ),
                            h(
                                "span", {
                                    style: {
                                        textDecoration: "underline",
                                        color: "#4b80fd",
                                        cursor: "pointer",
                                        'margin-left': "5px",
                                    },
                                    on: {
                                        click: () => {
                                            this.moveDown(this.data[params.index], params.index)
                                        }
                                    }
                                },
                                "下移"
                            ),
                        	h(
                                "span", {
                                    style: {
                                        textDecoration: "underline",
                                        color: "#4b80fd",
                                        cursor: "pointer",
                                        'margin-left': "5px",
                                    },
                                    on: {
                                        click: () => {  
                                            let ques = this.data[params.index];                                      	
                                            this.$router.push({ name: 'traindata', params: { qid: ques.id, train: JSON.stringify(ques) }})
                                        }
                                    }
                                },
                                "培训管理"
                            ),
                            h(
                                "span", {
                                    style: {
                                        textDecoration: "underline",
                                        color: "#4b80fd",
                                        cursor: "pointer",
                                        'margin-left': "5px",
                                    },
                                    on: {
                                        click: () => {
                                            this.show(params.index);
                                        }
                                    }
                                },
                                "编辑"
                            ),
                            h(
                                "span", {
                                    style: {
                                        textDecoration: "underline",
                                        color: "#4b80fd",
                                        cursor: "pointer",
                                        'margin-left': "5px",
                                    },
                                    on: {
                                        click: () => {
                                            this.removeData(params.index);
                                        }
                                    }
                                },
                                "删除"
                            )
                        ]);
                    }
        	}]
        }
    },
    methods: {
        removeData(index) {
            var self = this
            self.$Modal.confirm({
                title: '确认删除？',
                content: '',
                onOk: () => {
                    $.ajax({
                        url: "https://evp.51job.com/51job/api/1.0/index.php/minirs/Train/delTeain",
                        data: {
                            "id": self.data[index].id
                        },
                        type: "POST",
                        dataType: "json",
                        success: function(data) {

                            console.log(data);
                            if (data.code == 1) {
                                self.$Message.success('删除成功');
                                self.changepage()
                            }
                            else {
                                self.$Message.error('删除失败');
                            }
                        }
                    });
                },
                onCancel: () => {
                    this.$Message.info('取消删除');
                }
            });

        },
        moveUp(item, index) {
            $.ajax({
                url: "https://evp.51job.com/51job/api/1.0/index.php/minirs/train/sortTableData",
                type: "POST",
                data: {
                    "project_id": item.project_id,
                    id: item.id,
                    type: 1
                },
                dataType: "json",
                success: res => {
                    if(res.code === 1) {
                        // 上移成功
                        [this.data[index], [this.data[index - 1]]] = [this.data[index - 1], [this.data[index]]]
                        let copy = JSON.parse(JSON.stringify(this.data));
                        this.data = copy;
                    } else {
                        this.$Message.error(res.msg);
                    }
                }
            });
        },
        moveDown(item, index) {
            $.ajax({
                url: "https://evp.51job.com/51job/api/1.0/index.php/minirs/train/sortTableData",
                type: "POST",
                data: {
                    "project_id": item.project_id,
                    id: item.id,
                    type: 2
                },
                dataType: "json",
                success: res => {
                    if(res.code === 1) {
                        // 下移成功
                        [this.data[index], [this.data[index + 1]]] = [this.data[index + 1], [this.data[index]]]
                        let copy = JSON.parse(JSON.stringify(this.data));
                        this.data = copy;
                    } else {
                        this.$Message.error(res.msg);
                    }
                }
            });
        },
    	addTrainContentClick() {
            this.formData.type = 1;
    		this.addTrain = true;
    	},
        addTrainExamineClick() {
            this.formData.type = 2;
            this.addTrain = true;
        },
        handleImageClick() {
            $(".addinput").click();
        },
        handleImageClick2() {
            $(".addinput2").click();
        },
    	changepage(currentPage) {
            if (isNaN(currentPage)) {
                    currentPage = 1
                }
                var self = this

                var poid = localStorage.pid;
                $.ajax({
                    url: "https://evp.51job.com/51job/api/1.0/index.php/minirs/train/index",
                    data: {
                        "project_id": poid
                    },
                    type: "POST",
                    dataType: "json",
                    success: function(data) {
                        if (data.data != null) {
                            data.data.forEach(function(item){
                                item.picurl = "https://evp.51job.com/51job/api/51miniadmin/" + item.pic1;
                            })
                            self.data = data.data
                            // self.pageData.total = parseInt(data.datatotal)
                            // self.pageData.pageSize = 20
                            // self.pageData.current = currentPage
                        } else {
                            self.$Message.error(data.msg);
                        }
                    }
                });
    	},
        uploadImage(e) {
            console.log(e);

            var self = this;
            var file = e.target.files[0];
            var filesize = file.size;
            var filename = file.name;

            if (filesize > 2101440) {
                self.$Message.error("图片超过2m");
            }
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function(e) {
                var imgcode = e.target.result;
                self.imageData = imgcode;
                $.ajax({
                    url: "https://evp.51job.com/51job/api/51miniadmin/back.php?action=companyswiper",
                    data: {
                        file: self.imageData
                    },
                    type: "POST",
                    dataType: "json",
                    success: function(data) {
                        console.log(data);
                        self.formData.picurl = "https://evp.51job.com/51job/api/51miniadmin/" + data.url;
                        self.formData.pic1 = data.url
                    }
                });
            };
        },
        uploadImage2(e) {
            console.log(e);

            var self = this;
            var file = e.target.files[0];
            var filesize = file.size;
            var filename = file.name;

            if (filesize > 2101440) {
                self.$Message.error("图片超过2m");
            }
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function(e) {
                var imgcode = e.target.result;
                self.imageData = imgcode;
                $.ajax({
                    url: "https://evp.51job.com/51job/api/51miniadmin/back.php?action=companyswiper",
                    data: {
                        file: self.imageData
                    },
                    type: "POST",
                    dataType: "json",
                    success: function(data) {
                        console.log(data);
                        self.editData.picurl = "https://evp.51job.com/51job/api/51miniadmin/" + data.url;
                        self.editData.pic1 = data.url
                    }
                });
            };
        },
        show(index) {
            this.editQuestion = true;

            this.editData = this.data[index];
            console.log(this.editData)
        },
    	okEdit(name) {
            var poid = localStorage.pid;
                console.log(this.editData.id);
                this.$refs[name].validate(valid => {
                    if (valid) {
                        var self = this
                        $.ajax({
                            url: "https://evp.51job.com/51job/api/1.0/index.php/minirs/Train/updateTrain",
                            data: {
                                "project_id": poid,
                                "id": self.editData.id,
                                "qus": self.editData.qus,
                                "type": self.editData.type,
                                "title": self.editData.title,
                                "memo": self.editData.memo,
                                "integral": self.editData.integral,
                                "pic1": self.editData.pic1,
                            },
                            type: "POST",
                            dataType: "json",
                            success: function(data) {
                                console.log(data);

                                if (data.code == 1) {
                                    console.log(data);
                                    self.$Message.success('修改成功!')
                                    self.changepage(1);
                                }
                            }
                        });

                    } else {
                        this.$Message.error("编辑失败！");
                    }
                });
    	},
    	okAdd(name) {
            var poid = localStorage.pid;
                this.$refs[name].validate(valid => {
                    if (valid) {
                        var self = this

                        $.ajax({
                            url: "https://evp.51job.com/51job/api/1.0/index.php/minirs/Train/addTrain",
                            data: {
                                "project_id": poid,
                                "type": self.formData.type,
                                "title": self.formData.title,
                                "memo": self.formData.memo,
                                "integral": self.formData.integral,
                                "pic1": self.formData.pic1,
                                "qus": ""
                            },
                            type: "POST",
                            dataType: "json",
                            success: function(data) {
                                console.log(data);

                                if (data.code == 1) {
                                    console.log(data);
                                    
                                    self.$Message.success('新建成功!')
                                    self.changepage(1);
                                }
                            }
                        });

                    } else {
                        this.$Message.error("添加失败");
                    }
                });
                console.log(this.formData2);
    	}
    },
    created() {
        var poid = localStorage.pid;
        console.log(localStorage.pid)
        var self = this
        this.changepage()
    }
};
</script>
<style>
.avatar {
    height: 84px;
    width: 167px;
    display: block;
}
.avatar-uploader-icon {
    font-size: 36px;
    color: #8c939d;
    width: 167px;
    height: 84px;
    line-height: 84px;
    text-align: center;
    float: left;
    position: relative;
    border: 1px dashed #d9d9d9;
    background: #e5e5e5;
}
.input-item {
    margin-left: 45px;
    width: 250px;
}

.input-item2 {
    margin-left: 45px;
    width: 275px;
}

.formitem {
    margin-left: 30px;
}
</style>